package com.zhuzi.guicollect.controller.fx;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.validation.RequiredFieldValidator;
import com.zhuzi.guicollect.Main;
import com.zhuzi.guicollect.jsl.GetPage;
import com.zhuzi.guicollect.jsl.PeopleTopic;
import com.zhuzi.guicollect.ui.FavoriteView;
import com.zhuzi.guicollect.ui.LoginView;
import com.zhuzi.guicollect.utils.AlertUtils;
import com.zhuzi.guicollect.utils.IniUtils;
import com.zhuzi.guicollect.utils.SysUtils;
import com.zhuzi.guicollect.utils.ThreadPools;
import de.felixroske.jfxsupport.FXMLController;
import de.felixroske.jfxsupport.GUIState;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.kordamp.ikonli.fontawesome5.FontAwesomeSolid;
import org.kordamp.ikonli.javafx.FontIcon;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.URL;
import java.nio.file.Paths;
import java.util.ResourceBundle;

import static de.felixroske.jfxsupport.GUIState.getHostServices;

/**
 * @author MI
 * @ClassName MainController.java
 * @createTime 2021年10月31日 15:15:00
 */
@Slf4j
@FXMLController
public class MainController implements Initializable {
    @FXML
    public AnchorPane anPan;
    /*
     * 登录按钮  loginBtn
     */
    @FXML
    public Button loginBtn;
    @FXML
    public Hyperlink urlLink;

    @FXML
    public JFXButton favoBtn;
    /**
     * 收藏页面跳转按钮
     */
    @FXML
    public Button btnGoFav;
    /**
     * 大佬用户名
     */
    @FXML
    public JFXTextField userText;
    @FXML
    public JFXButton userTopicBtn;
    @FXML
    private Button collBtn;
    @FXML
    private Button dirSelBtn;
    @FXML
    public TextField dirText;
    @FXML
    private CheckBox onlyPageCheck;
    @FXML
    private CheckBox onlyPublishCheck;
    @FXML
    private TextField urlText;
    final DirectoryChooser dirChooser = new DirectoryChooser();


    @PostConstruct
    public void mainViewinit() {
        System.out.println("init");
        System.out.println(dirText == null);
    }

    public MainController() {
        System.out.println(Main.getStage());
        // 关闭的时候
        Main.getStage().setOnCloseRequest(event -> {
            saveDirToIniFile();
            Platform.exit();
            System.exit(0);
        });
    }

    private void saveDirToIniFile() {
        try {
            log.info("调用了保存方法");
            String text = dirText.getText();
            if (Paths.get(text).toFile().isDirectory()) {
                IniUtils.update("default", "dir", text);
            }
        } catch (Exception e) {
        }
    }

    @FXML
    void collect(ActionEvent event) {
        colButSet("采集进行中", false, true);
        ThreadPools.poolExecutor.execute(() -> {
            String url = urlText.getText();
            try {
                String delMsg = GetPage.isDeled(url);
                if (StringUtils.isNotBlank(delMsg)) {
                    AlertUtils.showAlter(Alert.AlertType.INFORMATION, delMsg);
                    colButSet("采集", true, false);
                    return;
                }
                GetPage.get(url, dirText.getText(), onlyPageCheck.isSelected(), onlyPublishCheck.isSelected());
            } catch (Exception e) {
                log.error("采集异常", e);
                AlertUtils.showAlter(Alert.AlertType.INFORMATION, "采集异常" + e.getMessage());
            }
            log.info("采集完成");
            IniUtils.update("default", "url", url);
            Platform.runLater(() -> {
                colButSet("采集", true, false);
            });
            // AlertUtils.showNotifications("提示", "采集完成", 3, Pos.BOTTOM_RIGHT, false);
            AlertUtils.showTrayNotification("提示", "采集完成", 3);
        });
    }

    @FXML
    void seleDir(MouseEvent event) {
        File file = dirChooser.showDialog(null);
        if (file != null) {
            dirText.setText(file.getAbsolutePath());
        }
    }

    /**
     * 更改按钮状态 文字
     *
     * @param title    按钮名字
     * @param addClass class
     * @param disable  状态
     */
    private void colButSet(String title, boolean addClass, boolean disable) {
        collBtn.setText(title);
        if (addClass) {
            collBtn.getStyleClass().remove("btn-info");
        } else {
            collBtn.getStyleClass().add("btn-info");
        }
        collBtn.setDisable(disable);
    }

    @Autowired
    ConfigurableApplicationContext applicationContext;

    Stage stage;

    /**
     * 登录
     *
     * @param actionEvent
     */
    public void openWinForLogin(ActionEvent actionEvent) {

        if (stage == null) {
            //TODO 登录
            LoginView loginView = applicationContext.getBean(LoginView.class);
            stage = new Stage();
            Scene scene = new Scene(loginView.getView());
            stage.setScene(scene);
            stage.initOwner(GUIState.getStage());
            //这个可以去除 icon图标
            stage.initStyle(StageStyle.UTILITY);
            stage.initModality(Modality.WINDOW_MODAL);
            stage.setTitle("登录");
            stage.setResizable(false);
        }
        stage.show();
        //TODO 登录切换窗体
        // Main.showView(LoginView.class);
    }

    /**
     * 只有这个方法中才能使用呢组件。其他方法无法使用组件，因为没有初始化完成
     */
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        log.info("初始化页面");
        try {
            //采集用户输入框校验
            RequiredFieldValidator validator = new RequiredFieldValidator();
            validator.setMessage("请输入");
            FontIcon warnIcon = new FontIcon(FontAwesomeSolid.EXCLAMATION_TRIANGLE);
            warnIcon.getStyleClass().add("info");
            validator.setIcon(warnIcon);
            userText.getValidators().add(validator);
            userText.focusedProperty().addListener((o, oldVal, newVal) -> {
                if (!newVal) {
                    userText.validate();
                }
            });


            String hisDir = IniUtils.read("default", "dir");
            if (!StringUtils.equals("d:/pic", hisDir) & SysUtils.isDirExit(hisDir)) {
                Platform.runLater(() -> {
                    dirText.setText(hisDir);
                });
            }
            //已经登录隐藏 登录按钮
            init();
            //设置文本框监听
            urlText.textProperty().addListener(hangeListener -> {
                urlLink.setText(urlText.getText());
            });
            //link 组件可访问浏览器
            urlLink.setOnAction(event -> {
                getHostServices().showDocument(urlLink.getText());
            });

            favoBtn.setOnAction(event -> {
                System.out.println("点击");
            });
        } catch (Exception e) {
        }
    }

    public void openDialog(ActionEvent actionEvent) {
        /*JFXAlert jfxAlert = new JFXAlert();
        jfxAlert.setOverlayClose(true);
        jfxAlert.setTitle("alert title");
        jfxAlert.setContentText("lalalalallalal");
        jfxAlert.setHeaderText("head");
        jfxAlert.showAndWait();*/
    }

    public void init() {
        log.info("main-view 显示{}", SysUtils.isLogin());
        if (SysUtils.isLogin()) {
            btnGoFav.setVisible(true);
            loginBtn.setVisible(false);
        } else {
            btnGoFav.setVisible(false);
            loginBtn.setVisible(true);
        }
    }

    /**
     * 跳转收藏页面
     *
     * @param actionEvent
     */
    public void goFavView(ActionEvent actionEvent) {
        Main.sysShowView(FavoriteView.class);
    }

    /**
     * 采集大佬主题
     *
     * @param actionEvent
     */
    public void calUserTopic(ActionEvent actionEvent) {
        if (!userText.validate()) {
            AlertUtils.showNotifications("提示", "请输入用户名", 3, Pos.CENTER_RIGHT);
            return;
        }
        ThreadPools.poolExecutor.execute(() -> {
            userTopicBtn.setDisable(true);
            PeopleTopic.getTopic(userText.getText(), dirText.getText());
            userTopicBtn.setDisable(false);
        });
    }
}
